import path from "node:path";
import { RunnerSpec, TaskHandler } from "../types";
import { resolvePath, ensureDir } from "../utils";
import { readBlueprint, writeJsonFile } from "../../../tools/data-processor";

export const blueprintCheckTask: TaskHandler = async (spec) => {
  const blueprintPath = spec.blueprint?.path;
  if (!blueprintPath) {
    throw new Error("blueprint.path is required for blueprint.check");
  }

  const absoluteBlueprint = resolvePath(blueprintPath);
  const data = await readBlueprint(absoluteBlueprint, ["designIntent", "configurableProps"]);
  const designIntent: any = data["designIntent"] ?? {};
  const sections = ["spacing", "colors", "typography"];
  const missingSections = sections.filter((section) => !designIntent || !designIntent[section]);

  const checklist = {
    blueprint: blueprintPath,
    hasConfigurableProps: Boolean(data["configurableProps"]),
    missingSections,
  };

  const reportPath = spec.report?.path ?? path.join(spec.output?.dir ?? "figma", "blueprint-checklist.json");
  await ensureDir(path.dirname(resolvePath(reportPath)));
  await writeJsonFile(reportPath, checklist);

  return {
    summary: missingSections.length
      ? `Blueprint missing sections: ${missingSections.join(", ")}`
      : "Blueprint designIntent sections complete",
    outputPaths: { checklist: reportPath },
    data: checklist,
  };
};
